
package pl.com.hme.kody.pocztowe.util;

import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * Tool that provides methods for convenient soft input (on-screen keyboard management).
 * 
 * @author Kamil Madejek
 */
public class SoftInputTool {

    /**
     * System service responsible for managing soft input.
     */
    private InputMethodManager inputMethodManager;

    /**
     * Preferably top level view of current views hierarchy. It provides special token that {@link InputMethodManager}
     * uses to authenticate its actions.
     */
    private View contentView;

    /**
     * {@link SoftInputTool}'s constructor.
     * 
     * @param inputMethodManager {@link InputMethodManager} service binded with current context.
     * @param contentView Top level view of current views hierarchy.
     */
    public SoftInputTool(InputMethodManager inputMethodManager, View contentView) {
        super();
        this.inputMethodManager = inputMethodManager;
        this.contentView = contentView;
    }

    /**
     * Hides on-screen keyboard. If it is already hidden calling this method doesn't have any effect.
     */
    public void forceHideSoftInput() {
        inputMethodManager.hideSoftInputFromWindow(contentView.getWindowToken(), 0);
    }

    /**
     * Sets {@link OnEditorActionListener} on given {@link TextView} so that submit operation (pressing hard or soft
     * enter key) performs click on given {@link View}. If you want to perform different action please consider creating
     * another method that works in similar manner.
     * 
     * @param textView {@link TextView}, which {@link OnEditorActionListener} is set by this method.
     * @param clickableView {@link View} on which click is performed.
     */
    public void makeTextViewPerformClickOnSubmit(TextView textView, final View clickableView) {
        textView.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                forceHideSoftInput();
                clickableView.requestFocus();
                clickableView.performClick();
                return true;
            }
        });
    }
}
